/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useReducer, Fragment } from "react";
import {
  Button,
  Table,
  Input,
  Row,
  Col,
  Select,
  Form,
  Modal,
  InputNumber,
  message,
  Popconfirm,
} from "antd";
import {
  getPro,
  getAllProType,
  addpro,
  getDetail,
  updatepro,
  deldetailimg,
  delPro,
} from "../../api/serve";
import { formatDate } from "../../util/tool";
import { stati } from "../../api/api";
import Uploadimg from "../../component/upLoad";
import MyEditor from "../../component/wangEditor/index";
import { array } from "prop-types";
import { connect } from "react-redux";
const initState = {
  productData: "",
  page: 1,
  // typeid: 0,
  orderbytype: "10",
  key: "",
  typeData: [], //商品分类数据
  type1Id: "",
  type2Id: "",
  total: "",
  skey: "",
  isModalOpen: false,
  firstId: "",
  second: "",
  Imglist: "",
  fuhtml: "",
  id: "",
  typeid: "",
};

function adminRedcuer(state = initState, action) {
  if (action) {
    return { ...state, ...action };
  }
  return state;
}
function CommodityManage({ auth }) {
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  const onUpdate = (rol) => {
    getDetail({ id: rol.id }, (res) => {
      const { detail } = res.data[0].data[0];
      dispatch({
        fuhtml: detail,
      });
    });
    forms.setFieldsValue({
      ...rol,
    });
    //根据typeid找对应的主分类id
    let fatherid = "";
    for (let i = 0; i < state.typeData.length; i++) {
      if (state.typeData[i].id === rol.typeid) {
        fatherid = state.typeData[i].fatherid;
        console.log(fatherid);
        break;
      }
    }
    fatherid = fatherid.split("-")[0];

    dispatch({
      isModalOpen: true,
      Imglist: rol.img,
      firstId: Number(fatherid),
      id: rol.id,
    });
  };
  const handleDelete = (row) => {
    console.log(row);
    let arr = [];
    arr = row.img.split(",");
    getDetail({ id: row.id }, (res) => {
      const data = res.data[0].data[0].detail;
      console.log(data);
      //该正则匹配所有的图片然后方便后续调用删除图片的接口
      let reg =
        /(?<=\<img src="http:\/\/8i98.com\/apidoc\/)vapi\/\d+\/[\w-\.]+\.[a-z]+(?=" alt="" data-href="" style=""\/\>)/g; // 找出详情里面的所有图片的正则;
      let arr1 = data.match(reg) || [];
      arr = [...arr, ...arr1];
      deldetailimg({ file: arr }, () => "");
      delPro({ id: row.id }, () => {
        init();
        message.success("删除成功");
      });
    });
  };
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "商品图片",
      dataIndex: "img",
      align: "center",
      render(data) {
        return (
          <Fragment>
            <img
              src={stati + data.split(",")[0]}
              alt=""
              style={{ width: "50px" }}
            />
          </Fragment>
        );
      },
    },
    {
      title: "商品名称",
      dataIndex: "title",
      align: "center",
    },
    {
      title: "价格",
      dataIndex: "price",
      align: "center",
    },
    {
      title: "折扣",
      dataIndex: "discount",
      align: "center",
    },
    {
      title: "库存",
      dataIndex: "stock",
      align: "center",
    },
    {
      title: "型号",
      dataIndex: "size",
      align: "center",
    },
    {
      title: "颜色",
      dataIndex: "color",
      align: "center",
    },
    {
      title: "分类",
      dataIndex: "typeid",
      align: "center",
      render(id) {
        let datas = state.typeData.filter(
          (item) =>
            item.typelevel === 1 && item.fatherid.search(state.type1Id) > -1
        );
        for (let i = 0; i < datas.length; i++) {
          if (id === datas[i].id) {
            return datas[i].title;
          }
        }
      },
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      align: "center",
      render: (value) => {
        return formatDate(value, "YYYY-MM-DD hh:mm:ss");
      },
    },
    {
      title: "商标",
      dataIndex: "brand",
      align: "center",
    },
    {
      title: "编辑",
      key: "action",
      align: "center",
      render: (_, record) => (
        <Fragment>
          {auth["/commodityManage"].update?.value && (
            <Button onClick={() => onUpdate(record)}>更新</Button>
          )}
          <Popconfirm
            title="确定删除?"
            onConfirm={() => handleDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            {auth["/commodityManage"].del?.value && (
              <Button danger>删除</Button>
            )}
          </Popconfirm>
        </Fragment>
      ),
    },
  ];
  const addProduct = () => {
    dispatch({
      isModalOpen: true,
    });
    forms.setFieldsValue({
      title: "",
      price: "",
      discount: "",
      weight: "",
      stock: "",
      color: "",
      brand: "",
      size: "",
      typeid: "",
      popular: "",
      sales: "",
    });
    dispatch({
      id: "",
      firstId: "",
      second: "",
      Imglist: "",
      fuhtml: "",
    });
  };
  const [state, dispatch] = useReducer(adminRedcuer, initState);
  const paginationProps = {
    //分页的配置
    current: state.page,
    pageSize: state.pageSize,
    total: state.total,
    onChange: (page, pageSize) => {
      //如果当前选择一页显示数据大于10条则将其恢复成最初状态
      if (pageSize > 10) {
        dispatch({
          page: 1,
          pageSize,
        });
        return;
      }
      dispatch({
        page,
        pageSize,
      });
    },
  };
  const init = () => {
    //初始数据的方法
    // if (state.key !== "" && state.type1Id === "") {
    //   dispatch({
    //     key: "",
    //   });
    // }
    getPro(
      {
        page: state.page,
        typeid: state.type2Id,
        orderbytype: state.orderbytype,
        key: state.key,
      },
      (res) => {
        dispatch({
          productData: res.data[0].data,
          total: res.data[1].data[0].count,
        });
      }
    );
  };
  const getInputValue = (e) => {
    // 获取搜索的内容
    const { value } = e.target;
    dispatch({
      page: 1,
      key: value,
    });
  };
  const handleSearch = () => {
    // 点击搜索的函数
    dispatch({
      skey: state.key,
    });
  };
  // 获取商品分类的id
  useEffect(function () {
    getAllProType((res) => {
      init();
      const data = res.data[0].data;
      const firstId = data.filter((item) => item.typelevel === 0)[0].id;
      dispatch({
        typeData: data,
        type1Id: firstId,
        type2Id: "",
      });
    });
  }, []);
  useEffect(
    // setHtmleditor(),
    function () {
      init();
    },
    [state.type2Id, state.page, state.skey]
  );
  const handleChange = (key, id) => {
    dispatch({
      [key]: id,
      key: "",
    });
    form.setFieldsValue({
      search: "",
    });
  };
  const onFinish = (values) => {
    if (state.id === "") {
      addpro(
        {
          ...values,
          typeid: state.typeid,
          img: state.Imglist,
          detail: state.fuhtml,
        },
        (res) => {
          message.success("添加成功");
          handleisOpen();
        }
      );
    } else {
      updatepro(
        {
          ...values,
          typeid: state.typeid,
          img: state.Imglist,
          detail: state.fuhtml,
          id: state.id,
        },
        (res) => {
          if (res.success) {
            message.success("更新成功");
            init();
            handleisOpen();
          }
        }
      );
    }
  };

  const handleisOpen = () => {
    dispatch({
      isModalOpen: false,
    });
  };
  const setImglist = (str) => {
    dispatch({
      Imglist: str,
    });
  };
  const setHtmleditor = (str) => {
    dispatch({
      fuhtml: str,
    });
  };
  return (
    <Fragment>
      <Form form={form}>
        <Row>
          <Col span={5}>
            {auth["/commodityManage"].add?.value && (
              <Button type="primary" onClick={addProduct}>
                添加
              </Button>
            )}
          </Col>
          <Col span={5}>
            <Form.Item
              name="search"
              rules={[
                {
                  required: true,
                  message: "请填写用户名",
                },
              ]}
            >
              <Input
                placeholder="请输入你要搜索的内容"
                onChange={(e) => getInputValue(e)}
              />
            </Form.Item>
          </Col>
          <Col>
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
          </Col>
          <Col offset={5}>
            <Select
              style={{ width: "100px" }}
              onChange={(value) => handleChange("type1Id", value)}
              value={state.type1Id}
            >
              {state.typeData
                .filter((item) => item.typelevel === 0)
                .map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.title}
                  </Select.Option>
                ))}
            </Select>
          </Col>
          <Col>
            {/* 进行一选择商品联动 选中一级分类由一级分类再选中二级分类*/}
            <Select
              onChange={(value) => handleChange("type2Id", value)}
              style={{ width: "100px" }}
              value={state.type2Id}
            >
              <Select.Option value="">所有</Select.Option>
              {state.typeData
                .filter(
                  (item) =>
                    item.typelevel === 1 &&
                    item.fatherid.search(state.type1Id) > -1
                )
                .map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.title}
                  </Select.Option>
                ))}
            </Select>
          </Col>
        </Row>
      </Form>
      <Table
        columns={columns}
        dataSource={state.productData}
        rowKey="id"
        pagination={paginationProps}
      />
      <Modal
        title="添加管理员账户"
        open={state.isModalOpen}
        centered={true}
        footer={null}
        closable={false}
        // style={{ width: "700px" }}
        width={1000}
      >
        <Form
          name="basic"
          initialValues={{
            remember: true,
          }}
          form={forms}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item label="商品名称" name="title">
            <Input placeholder="请输入商品名称" />
          </Form.Item>
          <Form.Item label="商品价格" name="price">
            <InputNumber />
          </Form.Item>
          <Form.Item label="商品折扣" name="discount">
            <InputNumber />
          </Form.Item>
          <Form.Item label="商品权重" name="weight">
            <Input placeholder="请输入权重" />
          </Form.Item>
          <Form.Item label="商品库存" name="stock">
            <InputNumber />
          </Form.Item>
          <Form.Item label="商品售卖情况" name="sales">
            <InputNumber />
          </Form.Item>
          <Form.Item label="商品欢迎程度" name="popular">
            <InputNumber />
          </Form.Item>
          <Form.Item label="商品颜色" name="color">
            <Input placeholder="请输入商品颜色" />
          </Form.Item>{" "}
          <Form.Item label="商品商标" name="brand">
            <Input placeholder="请输入商品商标" />
          </Form.Item>{" "}
          <Form.Item label="商品型号" name="size">
            <Input placeholder="请输入商品型号" />
          </Form.Item>{" "}
          <Form.Item label="主分类">
            <Select
              style={{ width: "100px" }}
              onChange={(value) => handleChange("firstId", value)}
              value={state.firstId}
            >
              {state.typeData
                .filter((item) => item.typelevel === 0)
                .map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.title}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item label="二级分类" name="typeid">
            <Select
              onChange={(value) => handleChange("typeid", value)}
              style={{ width: "100px" }}
              value={state.second}
            >
              {state.typeData
                .filter(
                  (item) =>
                    item.typelevel === 1 &&
                    item.fatherid.search(state.firstId) > -1
                )
                .map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.title}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item label="商品图片" name="img">
            <Uploadimg setImglist={setImglist} Imglist={state.Imglist} />
          </Form.Item>{" "}
          <Form.Item label="商品图片" name="imgs">
            <MyEditor setHtmls={setHtmleditor} fuhtml={state.fuhtml} />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: "10px" }}
            >
              Submit
            </Button>
            <Button type="primary" htmlType="button" onClick={handleisOpen}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Fragment>
  );
}
export default connect((state) => {
  let auth = {};
  if (state.user?.roleAuthority) {
    auth = JSON.parse(state.user.roleAuthority);
  }
  return { auth };
})(CommodityManage);
